'use strict';
const db = uniCloud.database()
const dbCmd = db.command
exports.main = async (event, context) => {
	// 获取数据库
	const billsCollection = db.collection('bills-list')
	const labelsCollection = db.collection('labels-list')
	// 获取所有label
	const allLabelsRes = await labelsCollection.where({
		owner:event.owner
	}).get()
	// 获取新的label
	let notInDBLabels = []
	let inDBLabels = []
	event.labels.forEach(label=>{
		// label如:'测试'
		if(!allLabelsRes.data.find(labelItem=>labelItem.value == label)){
			notInDBLabels.push(label)
		}else{
			inDBLabels.push(label)
		}
	})
	// 添加账单记录
	const addBillsRes = await billsCollection.add(event)
	// 添加新label记录
	let labelsAddRes
	if(notInDBLabels.length){
		labelsAddRes = await labelsCollection.add(notInDBLabels.map(item=>{
			return {
				value:item,
				owner:event.owner,
				count: 0,
			}
		}))
	}
	// 已有label自增1
	let labelsIncRes
	if(inDBLabels.length){
		for( let i = 0; i < inDBLabels.length; i++){
			labelsIncRes = await labelsCollection.where({
				value: inDBLabels[i],
				owner:event.owner,
			}).update({
			  count:dbCmd.inc(1)
			})
		}
	}
	return addBillsRes
};
